#import "BeanSelectionViewController.h"

@interface BeanSelectionViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property(nonatomic, strong) NSArray *beanData;
@end

@implementation BeanSelectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    VicSingleObject * single = [VicSingleObject getInstance];
    self.beanData = single.beansList;
    [self setupUI];
}

- (void)setupUI {
    // 标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"选择豆子（可多选）";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    
    // 取消按钮
    _cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor systemRedColor] forState:UIControlStateNormal];
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_cancelButton addTarget:self action:@selector(cancelSelection) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    // 确定按钮
    _confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [_confirmButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    _confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_confirmButton addTarget:self action:@selector(confirmSelection) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_confirmButton];
    
    // 表格视图
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.allowsMultipleSelection = YES;
    _tableView.layer.borderWidth = 0.5;
    _tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _tableView.layer.cornerRadius = 8;
    [self.view addSubview:_tableView];
    
    // 布局
    titleLabel.sd_layout
    .topSpaceToView(self.view, 20)
    .centerXEqualToView(self.view)
    .widthIs(200)
    .heightIs(44);
    
    _cancelButton.sd_layout
    .topSpaceToView(self.view, 20)
    .leftSpaceToView(self.view, 20)
    .widthIs(60)
    .heightIs(44);
    
    _confirmButton.sd_layout
    .topSpaceToView(self.view, 20)
    .rightSpaceToView(self.view, 20)
    .widthIs(60)
    .heightIs(44);
    
    _tableView.sd_layout
    .topSpaceToView(titleLabel, 10)
    .leftSpaceToView(self.view, 20)
    .rightSpaceToView(self.view, 20)
    .bottomSpaceToView(self.view, 20);
    
    // 设置预选状态
    [self preselectBeans];
}

- (void)preselectBeans {
    for (int i = 0; i < self.beanData.count; i++) {
        NSDictionary *bean = self.beanData[i];
        for (NSDictionary *selectedBean in self.selectedBeans) {
            if ([bean[@"beanValue"] isEqualToString:selectedBean[@"beanValue"]]) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                break;
            }
        }
    }
}

- (void)cancelSelection {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)confirmSelection {
    // 更新选中的豆子
    [self.selectedBeans removeAllObjects];
    NSArray *selectedIndexPaths = [self.tableView indexPathsForSelectedRows];
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        NSDictionary *bean = self.beanData[indexPath.row];
        [self.selectedBeans addObject:bean];
    }
    
    if (self.completion) {
        self.completion(self.selectedBeans);
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.beanData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"BeanCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    
    NSDictionary *bean = self.beanData[indexPath.row];
    cell.textLabel.text = bean[@"beanName"];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 多选逻辑已由tableView的allowsMultipleSelection属性处理
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 多选逻辑已由tableView的allowsMultipleSelection属性处理
}

@end
